package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author junbao
 * 把请求信息封装为Request对象（根据InputSteam输⼊流封装）
 */
public class Request {

    // 请求⽅式，⽐如GET/POST
    private String method;

    // 例如 /,/index.html
    private String url;

    private String host;

    private String port;

    // 其它属性从输入流中解析出来
    private InputStream inputStream;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Request() {
    }

    public Request(InputStream inputStream) throws IOException {
        // 从输入流中获取请求信息
        int count = 0;
        while(count == 0) {
            count = inputStream.available();
        }

        byte[] bytes = new byte[count];
        inputStream.read(bytes);

        String inputStr = new String(bytes);

        String[] lines = inputStr.split("\\n");
        // 获取第⼀⾏请求头信息
        String firstLineStr = lines[0];
        String[] strings = firstLineStr.split(" ");
        this.method = strings[0];
        this.url = strings[1];

        // 获取第二⾏请求头信息
        String secondLineStr = lines[1];
        String host = secondLineStr.split(" ")[1];
        String[] hostPort = host.split(":");
        if(hostPort.length > 1) {
            this.host = hostPort[0];
            this.port = hostPort[1];
        }else{
            this.host = hostPort[0];
            this.port = "8080";
        }

        System.out.println("-->host:" + this.host);
        System.out.println("-->port:" + port);
        System.out.println("-->method:" + method);
        System.out.println("-->url:" + url);
    }
}
